package com.lftea.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.lftea.dao.IStorekHouseDAO;
import com.lftea.dao.IStockPileDAO;
import com.lftea.po.StoreHouse;
import com.lftea.util.StringUtils;

@Repository("storeHouseDAOImpl")
public class StoreHouseDAOImpl implements IStorekHouseDAO {

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	@Resource(name = "stockPileDAOImpl")
	private IStockPileDAO stockPileDAOImpl;

	public List<StoreHouse> findAll() {
		String sql = "select * from StoreHouse";
		return jdbcTemplate.query(sql, new StoreHouseMapper());
	}

	public StoreHouse findById(long storeHouseId) {
		String sql = "select * from StoreHouse where StoreHouse_ID=?";
		return (StoreHouse) jdbcTemplate.query(sql,
				new Object[] { storeHouseId }, new StoreHouseMapper());
	}

	public boolean isEmpty(StoreHouse storeHouse) {
		long storeHouseId = storeHouse.getId();
		long total = stockPileDAOImpl.findTotalByStoreHouseId(storeHouseId);
		return total > 0 ? false : true;
	}

	public void remove(StoreHouse storeHouse) {
		long storeHouseId = storeHouse.getId();
		// 先删除库存明细
		stockPileDAOImpl.removeByStoreHouseId(storeHouseId);
		// 再删除仓库
		String sql = "delete StoreHouse where StoreHouse_ID=?";
		jdbcTemplate.update(sql, new Object[] { storeHouseId });
	}

	public void save(StoreHouse storeHouse) {
		long storeHouseId = storeHouse.getId();
		String name = StringUtils.toISO(storeHouse.getName());
		String address = StringUtils.toISO(storeHouse.getAddress());
		String createDate = storeHouse.getCreateDate();

		String sql = "select count(*) from StoreHouse where StoreHouse_ID=?";
		int result = jdbcTemplate
				.queryForInt(sql, new Object[] { storeHouseId });
		Object[] params = null;
		if (result > 0) {
			sql = "update StoreHouse set Name=?,Address=?,CreateDate=? where StoreHouse_ID=?";
			params = new Object[] { name, address, createDate, storeHouseId };
		} else {
			sql = "insert into StoreHouse(Name,Address,CreateDate) values(?,?,?)";
			params = new Object[] { name, address, createDate };
		}
		jdbcTemplate.update(sql, params);
	}

	private final class StoreHouseMapper implements RowMapper<StoreHouse> {

		public StoreHouse mapRow(ResultSet rs, int rowNum) throws SQLException {
			StoreHouse storeHouse = new StoreHouse();
			storeHouse.setId(rs.getLong("StoreHouse_id"));
			storeHouse.setName(StringUtils.toGBK(rs.getString("name")));
			storeHouse.setAddress(StringUtils.toGBK(rs.getString("address")));
			storeHouse.setCreateDate(String.valueOf(rs.getObject("createDate")));
			return storeHouse;
		}

	}
}
